package com.weixin.paleituo.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.GoodsDetailsActivity;
import com.weixin.paleituo.adapter.StoreHomeAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseFragment;
import com.weixin.paleituo.bean.CarouselBean;
import com.weixin.paleituo.bean.HotStoreGoods;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.YRecycleview;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

/**
 * Author yichao
 * Time  2018/4/4 10:57
 * Dest  店铺首页
 */

public class StoreHomeFragment extends BaseFragment {


    @BindView(R.id.yrecycleview_store_home_fragment)
    YRecycleview mYrecycleviewStoreHomeFragment;
    private View mHeadView;
    private ConvenientBanner mConvenientBanner;
    private int mStoreId;
    private LoadingPagerHead mLoadingPagerHead;
    private int currentPage=1;
    List<HotStoreGoods> mHotStoreGoods=new ArrayList<>();
    private StoreHomeAdapter mStoreHomeAdapter;

    @Override
    public View initView(Context context) {
        if (mLoadingPagerHead==null) {
            mHeadView = UIUtils.inflate(context, R.layout.layout_store_head);
            mConvenientBanner = mHeadView.findViewById(R.id.id_cb_layout_store_head);
            mLoadingPagerHead = new LoadingPagerHead(context) {
                @Override
                protected void close() {

                }

                @Override
                protected View createSuccessView() {
                    return UIUtils.inflate(mContext, R.layout.store_home_fragment);
                }
                @Override
                protected void reLoading() {
                    retry();

                }
            };
        }else {
            ViewGroup viewGroup= (ViewGroup) mLoadingPagerHead.getParent();
            viewGroup.removeView(mLoadingPagerHead);
        }

        return mLoadingPagerHead;
    }

    /**
     * 重新加载
     */
    private void retry() {
        currentPage=1;
        Observable<StatusCode<List<HotStoreGoods>>> storeHotgoodsObservable = ApiUtils.getApi().getStoreHotgoods(Contans.defaultToken, mStoreId, Contans.rows, 1,BaseApplication.getNewUserId());


        HttpUtil.getInstance().toSubscribe(storeHotgoodsObservable, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {


            @Override
            protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {


                List<HotStoreGoods> hotStoreGoods = listStatusCode.getData();
                if (hotStoreGoods!=null &&hotStoreGoods.size()>0){
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                    mHotStoreGoods.clear();
                    mHotStoreGoods.addAll(hotStoreGoods);
                    mStoreHomeAdapter.notifyDataSetChanged();




                }else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                }
            }

            @Override
            protected void _onError(String message) {

                mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                ToastUtils.makeText(message);



            }
        },"",lifecycleSubject,false,true);


    }


    @Override
    protected void initData() {
        super.initData();
        Bundle arguments = getArguments();
        mStoreId = arguments.getInt(Contans.INTENT_EXTRA);
        ArrayList<CarouselBean> carouselBeans = arguments.getParcelableArrayList(Contans.INTENT_DATA);
        mHotStoreGoods.clear();
        mStoreHomeAdapter = new StoreHomeAdapter(mContext, mHotStoreGoods);
        //   HeaderAndFooterWrapper headerAndFooterWrapper=new HeaderAndFooterWrapper(storeHomeAdapter);
        //  headerAndFooterWrapper.addHeaderView(mHeadView);
        mConvenientBanner.setPages(new CBViewHolderCreator<ImageViewHolder>() {
            @Override
            public ImageViewHolder createHolder() {
                return new ImageViewHolder();
            }
        }, carouselBeans)
                .setPageIndicator(new int[]{R.drawable.noselect_circle_shape, R.drawable.select_circle_shape}) //设置两个点作为指示器
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL); //设置指示器的方向水平  居中
        mConvenientBanner.setCanLoop(true);
        mYrecycleviewStoreHomeFragment.addHeadView(mHeadView);
        mYrecycleviewStoreHomeFragment.setReFreshEnabled(false);
        mYrecycleviewStoreHomeFragment.setAdapter(mStoreHomeAdapter);
        mYrecycleviewStoreHomeFragment.setLayoutManager(new LinearLayoutManager(mContext));
        mYrecycleviewStoreHomeFragment.setItemAnimator(new DefaultItemAnimator());
        mYrecycleviewStoreHomeFragment.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {

                Observable<StatusCode<List<HotStoreGoods>>> storeHotgoods = ApiUtils.getApi().getStoreHotgoods(Contans.defaultToken, mStoreId, Contans.rows, currentPage + 1, BaseApplication.getNewUserId());
                HttpUtil.getInstance().toSubscribe(storeHotgoods, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {
                    @Override
                    protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {

                        mYrecycleviewStoreHomeFragment.setloadMoreComplete();
                        List<HotStoreGoods> storeGoods = listStatusCode.getData();
                        if (storeGoods!=null &&storeGoods.size()>0){
                            currentPage++;
                            mHotStoreGoods.addAll(storeGoods);
                            mStoreHomeAdapter.notifyDataSetChanged();
                        }else {
                            ToastUtils.makeText("没有更多数据了");
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        mYrecycleviewStoreHomeFragment.setloadMoreComplete();


                    }
                },"",lifecycleSubject,false,true);


            }
        });
retry();

    }


    public static Fragment getInstance(int storeId, List<CarouselBean> carouselBeans) {
        StoreHomeFragment storeHomeFragment = new StoreHomeFragment();

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(Contans.INTENT_DATA, (ArrayList<? extends Parcelable>) carouselBeans);
        bundle.putInt(Contans.INTENT_EXTRA, storeId);
        storeHomeFragment.setArguments(bundle);
        return storeHomeFragment;
    }

    public class ImageViewHolder implements Holder<CarouselBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, CarouselBean data) {
            Glide.with(context).load(data.getUrl()).into(imageView);
         final    int houseid = data.getGoodsId() ;
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        GoodsDetailsActivity.startActivity(mContext,houseid);

                }
            });

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mConvenientBanner!=null){

        mConvenientBanner.startTurning(2000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mConvenientBanner!=null){
            mConvenientBanner.startTurning(2000);
        }
    }
}
